package top.codestudy

import org.gradle.api.Plugin
import org.gradle.api.Project

class FileLinesPlugin implements Plugin<Project> {

    static long totalCount(File file, boolean includeBlank) {
        def count = 0
        if (file.canRead()) {
            file.eachLine { line ->
                if (includeBlank) {
                    count++
                } else {
                    if (!line.empty) {
                        count++
                    }
                }
            }
        }
        return count
    }

    void apply(Project project) {
        def extension = project.extensions.create('fileExtensionName', FileLinesPluginExtension)
        println "project path ==> " + project.getPath() + " == " + project.getDepth()

        project.task('calculateLinesOfCode') {
            doLast {
                if (extension.extensionName) {
                    def list = new ArrayList<>()
                    extension.extensionName.forEach { fileExtensionName ->
                        list.add("**/*.$fileExtensionName")
                    }
                    def includeBlank = extension.includeBlankLine
                    def detail = extension.detail
                    println "includeBlank = $includeBlank "
                    /**
                     * 1.获取所有子模块
                     * 2.统计各个子模块的文件的行数，排除空行
                     */
                    def rootDir = project.rootDir
                    def subProjects = project.getRootProject().getSubprojects()
                    def allTotal = 0
                    subProjects.forEach { subProject ->
                        def configurableFileTree = subProject.fileTree("src")
                        def fileTree = configurableFileTree.matching { pattern ->
                            pattern.include(list)
                        }
                        def total = 0
                        fileTree.getFiles().forEach { file ->
                            def temp = totalCount(file, includeBlank)
                            total += temp
                            if (detail){
                                println "Module ${subProject.name}:  File name is ${file.name} ; count ==> " + temp
                            }
                        }
                        println "Module ${subProject.name}: The lines of code is $total "
                        allTotal += total
                    }
                    println "The number of lines of code for all projects is $allTotal"
                } else {
                    println "sourceCodeDirectory not config!"
                }


            }
        }
    }
}
